webix
		.ready(function() {
			var projectS = JSON.parse($("#projects").val());
			  webix.Date.startOnMonday = true;
			  webix.Date.dateToStr("%H:%i:00");
			  var calendar_window=webix.ui({
				    view:"window",
				    id:"my_window",
				    position:'center',
				    move:true,
				    head:{
				      view:"toolbar",margin:-4,cols:[
				        {},
				        { view:"icon", icon:"times-circle",click:"$$('my_window').hide();"}
				      ]
				    },
				    body:{
				      view:"calendar",
				      id:"my_calendar",
				      type:"time",
				    }, 
				  });
			  $$('my_calendar').attachEvent("onAfterDateSelect", function(date){
				      var format = webix.Date.dateToStr("%H:%i:00");
				      var times = format(date); //2012.05
				      $$("downtime").setValue(times);
				      $$("my_window").hide();
				  });
			var my_templaet = {
				template : "<span style='font-size:20px; font-weight:bold; color:#3498DB'; >生产计划</span>&nbsp;/&nbsp;&nbsp;ProductionPlan",
				height : 45,
				borderless : true
			};
			var my_toolbar = {
				view : "toolbar",
				elements : [ {
					view : "text",
					id : "jhmc",
					label : "计划名称",
					width : 260,
					labelWidth : 80
				}, {
					view : "datepicker",
					id : "startDate",
					timepicker : true,
					label : "计划开始",
					labelAlign : "right",
					name : "end",
					stringResult : true,
					format : "%Y-%m-%d %H:%i",
					width : 240
				}, {
					view : "datepicker",
					id : "endDate",
					timepicker : true,
					label : "计划结束",
					labelAlign : "right",
					name : "end",
					format : "%Y-%m-%d %H:%i",
					stringResult : true,
					width : 240
				}, {
					view : "button",
					value : "查询",
					width : 100,
					click : "select"
				}, {
					view : "button",
					value : "安排计划",
					width : 100,
					click : "plan"
				}, {
					view : "button",
					value : "保存修改",
					width : 100,
					click : "save"
				}  ]
			};
			var my_treetable = {
				view : "datatable",
				id : "my_treetable",
				columns : [{
					id : "plan_id",
					header :  "计划id",
					fillspace : true,
					hidden:true
				},  {
					id : "plan_name",
					header : [ "计划名称", {
						content : "textFilter",
						placeholder : "请输入计划名称进行查询",
					} ],
					fillspace : true
				},{
					id : "project_id",
					header :  "项目id",
					fillspace : true,
					hidden:true
				},  {
					id : "project_name",
					header : [ "项目名称", {
						content : "textFilter",
						placeholder : "请输入项目名称进行查询",
					} ],
					fillspace : true
				}, {
					id : "plan_start_date",
					header : "开始时间",
					fillspace : true
				}, {
					id : "plan_end_date",
					header : "结束时间",
					fillspace : true
				},  {
					id : "is_auto",
					header : "是否定时下发",
					fillspace : true,
					template : function(obj,type) {
						if (obj.is_auto == "0") {
							return "否";
						} else if (obj.is_auto == "1") {
							return "下发时间 ："+obj.issuedTime;
					}
				}
				},  {
					id : "process_id",
					header : "工序",
					fillspace : true,
					hidden:true
				},  {
					id : "process_name",
					header : "工序",
					fillspace : true
				},  {
					id : "class_id",
					header : "班别id",
					fillspace : true,
					hidden:true
				}, {
					id : "class_name",
					header : "班别",
					fillspace : true
				},{
					id : "yield",
					header : "产能",
					fillspace : true,
					editor:"text"
				},
				{id:"cz",header:"操作",template:"<a class='btn1' href='javascript:void(0);' onclick=\"updatePlanById('#plan_id#','#process_id#','#class_id#')\">编辑</a>&nbsp;&nbsp;&nbsp;<a class='btn1' href='javascript:void(0);' onclick=\"delPlanById('#plan_id#')\">删除</a>",width:100},
				],
				height:740,
			    tooltip:true,
			    data:{
			      data:"",
			      spans:[]
			    },
			    spans:true,
			    select:"cell",
			};

			var body = new webix.ui({
				fullscreen : true,
				container : "body",
				type : "line",
				id : "mylayout",
				rows : [ my_templaet, my_toolbar, my_treetable ],// ----rows结束----
			});// ---webix.ui结束----
			webix.ajax().sync().post("getPlanList", "", function(text, xml, xhr){
			    var text1=JSON.parse(text); 
			    var data = new webix.DataCollection({data:text1.data});
			    $$('my_treetable').data.sync(data);
			    chuli(text1.data);
			  });
			// 原料入库表单模态框实现
			var addForm = [ {
				margin : 50,
				cols : [ {
					view : "text",
					id : "plan_name",
					name : "plan_name",
					width : 300,
					label : "计划名称：",
					labelWidth : 100
				}, {
					view : "combo",
					id : "project_id",
					name : "project_id",
					width : 300,
					label : "选择项目：",
					labelWidth : 100,
					options : projectS.data
				}, ]
			}, {
				margin : 50,
				cols : [ {
					view : "datepicker",
					timepicker : true,
					stringResult : true,
					id : "start_date",
					name : "start_date",
					width : 300,
					label : "开始时间：",
					labelWidth : 100,
					format : "%Y-%m-%d"
				}, {
					view : "datepicker",
					timepicker : true,
					stringResult : true,
					id : "end_date",
					name : "end_date",
					width : 300,
					label : "结束时间：",
					labelWidth : 100,
					format : "%Y-%m-%d"
				} ]
			},{
				margin : 50,
				cols : [ {
					view : "radio",
					timepicker : true,
					stringResult : true,
					id : "is_auto",
					name : "is_auto",
					value:0,
					width : 300,
					label : "定时下发：",
					labelWidth : 100,
					options : [ {id:1,value:"是"},{id:0,value:"否"} ]
				}, {
					view : "text",
					id : "downtime",
					name : "downtime",
					width : 300,
					label : "下发时间：",
					labelWidth : 100,
					click:"select_time",
					hidden:true
				} ]
			},
			// 领料表格
			{
				view : "datatable",
				id : "tableA",
				editable : true,
				tooltip : true,
				height : 200
			}, {
				id:"save",
				view : "button",
				value : "确定",
				width : 80,
				click : "sure",
				css : {
					"margin-left" : "580px!important"
				}
			} ];
			var head = {
				view : "toolbar",
				margin : -4,
				cols : [ {
					view : "label",
					label : "安排计划"
				}, {
					view : "icon",
					icon : "times-circle",
					click : "$$('win3').hide();"
				} ]
			};
			var body = {
				view : "form",
				id : "form",
				autoheight : true,
				width : 700,
				margin : 20,
				elements : addForm
			};
			webix.ui({
				view : "window",
				id : "win3",
				position : "center",
				modal : true,
				move : true,
				head : head,
				body : body
			});
			// 查询清空时显示所有数据实现
			$$("jhmc").attachEvent(
					"onTimedKeyPress",
					function() {
						var value = this.getValue();
						var startDate = $$("startDate").getText();
						var endDate = $$("endDate").getText();
						if (value == "" && startDate == ""
								&& endDate == "") {
							location.reload();
						}
					});
			$$("startDate").attachEvent(
					"onChange",
					function() {
						var value = this.getValue();
						var name2 = $$("plan_name").getValue();
						var endDate = $$("endDate").getText();
						if (value == "" && name2 == ""
								&& endDate == "") {
							location.reload();
						}
					});
			$$("endDate").attachEvent(
					"onChange",
					function() {
						var value = this.getValue();
						var name2 = $$("plan_name").getValue();
						var startDate = $$("startDate").getText();
						if (value == "" && name2 == "" && startDate == ""
								) {
							location.reload();
						}
					});
			
			$$("is_auto").attachEvent(
					"onChange",
					function() {
						var value = this.getValue();
						if(value==0){
								$$("downtime").hide();
						}else{
							$$("downtime").show();
						}
					});
		});

function plan() {
	$$('win3').show();
	// 选择项目
	$$("form").elements["project_id"].attachEvent("onChange", function(newv,
			oldv) {
		var params = {};
		params.project_id = newv;
		webix.ajax().sync().post("getProcessListByProjectId", params,
				function(text, xml, xhr) {
					var data = JSON.parse(text);
					columnD = data.tableHead;
					tableD = data.tableBodys;
				});
		$$('tableA').define("columns", columnD);
		$$('tableA').refresh();
		//var data = new webix.DataCollection({
		 //	data : tableD
		 //});
		//$$("tableA").data.sync(data);
$$('tableA').clearAll();
 $$('tableA').define("data",tableD);
 $$("tableA").refresh();
		// });
	});
}

function sure() {
	
	$$("save").disable();
	var params = {};
	var tableValues = "";
	var flag1 = false;
	var formdata = $$("form").getValues();
	var d1 = new Date(formdata.start_date.replace(/\-/g, "\/"));
	var d2 = new Date(formdata.end_date.replace(/\-/g, "\/"));
	
	if (formdata.plan_name == "") {
		$$("save").enable();
		alert("请输入计划名称...");
		return false;
	} else if (formdata.project_id == "") {
  		$$("save").enable();
		alert("请选择项目...");
		return false;
	} else if (formdata.start_date == "") {
  		$$("save").enable();
		alert("请输入开始时间...");
		return false;
	} else if (formdata.end_date == "") {
  		$$("save").enable();
		alert("请输入结束时间...");
		return false;
	} else if (d1 > d2) {
  		$$("save").enable();
		alert("开始时间不能大于结束时间！");
		return false;
	} else if (formdata.is_auto == "1" && formdata.downtime == "") {
  		$$("save").enable();
		alert("请输入下发时间！");
		return false;
	} else {
		flag1 = true;
	}
	var i = 0;
	if (flag1) {
		$$("tableA").eachRow(function(row) {
			$$("tableA").editStop();
			// 遍历每一行，得到表格数据
			var rowObj = $$("tableA").getItem(row);
			tableValues += JSON.stringify(rowObj) + "@";
			i++;
		});
	}
 	params.tableValues = tableValues;
	params.plan_name = formdata.plan_name;
	params.project_id = formdata.project_id;
	params.start_date = formdata.start_date;
	params.end_date = formdata.end_date;
	params.is_auto = formdata.is_auto;
	params.downtime = formdata.downtime;
	webix.ajax().sync().post("addPlan", params, function(text, xml, xhr) {
		var data = JSON.parse(text);
		if(data.ret>0){
			alert("添加成功！");
			location.reload();
		}else{
			alert(data.msg);
	  		$$("save").enable();
		}
	});
}
// 查询实现
function select() {
	var storge_date1 = $$("startDate").getText();
	var storge_date2 = $$("endDate").getText();
	var d1 = new Date(storge_date1.replace(/\-/g, "\/"));
	var d2 = new Date(storge_date2.replace(/\-/g, "\/"));
	if (storge_date1 != "" && storge_date2 != "" && d1 > d2) {
		alert("开始时间不能大于结束时间！");
		return false;
	}

	var pici = $$("jhmc").getValue();
	var params = {};
	params.start_date = storge_date1;
	params.end_date = storge_date2;
	params.plan_name = pici;
	webix.ajax().sync().post("getPlanList", params, function(text, xml, xhr){
	    var text1=JSON.parse(text); 
	    var data = new webix.DataCollection({data:text1.data});
	    $$('my_treetable').data.sync(data);
	    chuli(text1.data);
	  });
}
 
function callback(data) {
	var text1 = JSON.parse(data);
	$$('my_treetable').clearAll();
    $$('my_treetable').data.sync(data);
	$$("my_treetable").refresh();
}
function delPlanById(id){
	webix.alert({
        title: "警告",
        text: "确认要删除该计划吗？删除之后不可恢复。",
        ok: "确定",
        cancel:"取消",
        type: "confirm-warning",
        callback: function(result) {
            if (result == true) {
            	var params = {};
            	params["plan_id"]=id;
            	webix.ajax().sync().post("delPlanById", params, function(text, xml, xhr) {
            		alert("执行完毕");
            		location.reload();
            	});
            }
        }
	});
}
function select_time(){
	$$("my_window").show();
}
function chuli(data){
	  var d=data;
	  // console.log(d);
	  d.sort( function(a, b){   
	    return (a["plan_name"]) > (b["plan_name"])? 1 : (a[ "plan_name"]) == (b[ "plan_name" ]) ? 0 : -1;   
	}); 
	  var count=0;
	  var arryNew1=Array();
	  var arryNew2=Array();
	  var arryNew3=Array();
	  var arryNew4=Array();
	  var temp="";
	  var b1=Array();
	  var b2=Array();
	  var b3=Array();
	  var b4=Array();
	  var b5=Array();
	  var b6=Array();
	  var ddd=0;
	  var ccc=0;
	  var eee=0;
	  var fff=0;
	  var ggg=0;
	  var hhh=0;
	  for(var i=0;i<d.length;i++){
	    // 得到项目重复情况
	      if(b1[i]!=-1){
	        temp=d[i].plan_name;
	        for(var j=0;j<d.length;j++){
	          if(temp==d[j].plan_name){
	            count++;
	            b1[j] = -1;
	          }
	        }
	        arryNew1.push(count);// 把这次循环的元素以及出现的次数保存到新的数组中
	        count = 0;// 让count的值重新等于0
	      }
	  }
	// 用于将数据排序得到调理好的数据
	var sortArray1=new Array();
	var sortArray2=new Array();
	var sortArray3=new Array();
	getSort(arryNew1,sortArray1,"process_name",d);
	  for(var k=0;k<arryNew1.length;k++){
	 ccc=ddd+arryNew1[k];
	  for(var j=ddd;j<ccc;j++){
	    if(b2[j]!=-1){
	      temp=d[j].process_name;
	      for(var i=ddd;i<ccc;i++){
	        // 判断
	       if(temp==d[i].process_name){
	          count++;
	         b2[i] = -1;
	        }
	      } 
	      arryNew2.push(count);// 把这次循环的元素以及出现的次数保存到新的数组中
	      count = 0;// 让count的值重新等于0
	    }
	  }
	  ddd=ccc;
	}
	// console.log(arryNew2);
	getSort(arryNew2,sortArray2,"classes_name",d);
	  for(var k=0;k<arryNew2.length;k++){
	   eee=fff+arryNew2[k];
	  for(var j=fff;j<eee;j++){
	    if(b3[j]!=-1){
	      temp=d[j].classes_name;
	      for(var i=fff;i<eee;i++){
	        // 判断
	       if(temp==d[i].classes_name){
	        count++;
	         b3[i] = -1;
	        }
	      } 
	      arryNew3.push(count);// 把这次循环的元素以及出现的次数保存到新的数组中
	      count = 0;// 让count的值重新等于0
	    }
	  }
	  fff=eee;
	}
	  $$('my_treetable').clearAll();
	  $$('my_treetable').define("data",d);
	  $$("my_treetable").refresh();
	　　span(arryNew1,"plan_name");
	　　span(arryNew1,"project_name");
	　　span(arryNew1,"plan_start_date");
	　　span(arryNew1,"plan_end_date");
	　　span(arryNew1,"is_auto");
	　　span(arryNew2, "process_name");
	　　span(arryNew3, "classes_name");

	 $$("my_treetable").refresh();
	}

function span(arryNew1,key){
	  var e1;
	  var f1=0;
	  var f11=0;
	  for(var i=0;i<arryNew1.length;i++){
	        f11=f1+f11;
	        e1=$$("my_treetable").getIdByIndex(f11);
	        $$("my_treetable").addSpan([
	           [e1, key, 1, arryNew1[i]],
	        ]);
	        f1=arryNew1[i];
	　　}
	}
	function getSort(arryNew2,sortArray2,key,d){
	var p3=0;
	var p4=0;
	  for(var i=0;i<arryNew2.length;i++){
	          sortArray2[i]=new Array();
	          p3=p3+p4;
	          for(var j=p3;j<p3+arryNew2[i];j++){
	            sortArray2[i][j]=d[j];
	          }
	          sortArray2[i].sort( function(a, b){   
	            return (a[key]) > (b[key])? 1 : (a[key]) == (b[key]) ? 0 : -1;  
	          });
	          var l=0;
	          for(var k=p3;k<p3+arryNew2[i];k++){
	            d[k]=sortArray2[i][l++];
	          } 
	          p4=arryNew2[i];
	  　　}
	}
	function updatePlanById(plan_id,process_id,classes_id){
		  if(plan_id&&process_id&&classes_id){
			  var dt=$$("my_treetable");
			  dt.eachRow(function(row){
				if(dt.getItem(row).class_id==classes_id&&dt.getItem(row).process_id==process_id&&dt.getItem(row).plan_id==plan_id){
				  dt.editRow(row);
				  dt.addRowCss(row, "newRow2");
				}
			  });
		  }
	}
	function save(){
		var jsonarr =[];
		var sb = new StringBuffer();
		 var dt=$$("my_treetable");
	     var params = {};
		 var flag = true;
		 if(flag){
		 dt.editStop();
		  dt.eachRow(function(row){
			  if(dt.hasCss(row,"newRow2")==true){
				 var  param=dt.getItem(row);
				  if(param.yield==""){
					  alert("请填写产能...");
					  return false;
				  }
				  var str = JSON.stringify(param);
				  jsonarr.push(param);

			         
			  }
	    });
		  flag = false;
		  if(JSON.stringify(jsonarr)!=""){
			  alert(jsonarr);
			  params.jsonArr = JSON.stringify(jsonarr);
			  webix.ajax().sync().post("updatePlan", params, function(text, xml, xhr){
				  alert("执行完毕");
				  location.reload();
				  flag = true;
			  });
		  }else{
			  alert("未获取到修改内容...");
			  flag=true;
		  }
		 }
	}